package com.example.ResumeWorkPlatform.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;

/**
 * @ClassName: FileUploadUtil
 * @Description: 上传文件
 * @Copyright: smartlab411
 * @Author wangfuxin
 * @DateTime 2020-02-04 12:27:25
 */
public class FileUploadUtil {

	private static final Logger log = LoggerFactory.getLogger(FileUploadUtil.class);

	/**
	 * @param file        上传文件
	 * @param saveAddress 保存文件路径
	 * @return
	 */
	public static JSONObject fileTaskFileURL(MultipartFile file, String saveAddress) {
		// TODO 1.用户文档上传
		JSONObject return_data = new JSONObject();
		// 4.获取文件后缀
		String[] filenamesplit = file.getOriginalFilename().split("\\.");
		String fileType = filenamesplit[filenamesplit.length - 1].replaceAll(" ", "");
		// 5.拼接保存文件名
		String saveFileName = System.currentTimeMillis() + "." + fileType;
		// 6.文件保存路径
		String absoluteAddress = saveAddress + saveFileName;
		try {
			File fileData = new File(absoluteAddress);
			if (!fileData.exists()) {
				fileData.createNewFile();
			}
			FileOutputStream fp = new FileOutputStream(absoluteAddress);
			fp.write(file.getBytes());
			fp.flush();
			fp.close();
			fileData = null;
			fp = null;
		} catch (Exception e) {
			return_data.put("res", false);
			return_data.put("exception", file.getOriginalFilename() + "保存失败");
			log.error(file.getOriginalFilename() + "保存失败.");
			return return_data;
		}
		System.gc();
		return_data.put("res", true);
		return_data.put("fileName", saveFileName);
		return_data.put("absoluteAddress", absoluteAddress);// 文件路径
		return return_data;
	}

	/**
	 * 复制单个文件
	 * 
	 * @param oldPath String 原文件路径 如：/Users/wangfuxin/Desktop/项目计划跟踪表.jpg
	 * @param newPath String 复制后路径 如：/Users/wangfuxin/Desktop/1.jpg
	 * @return boolean
	 */
	public static Boolean copyFile(String oldPath, String newPath) {
		// TODO 复制单个文件
		try {
//			int bytesum = 0;
			int byteread = 0;
			File oldfile = new File(oldPath);
			if (oldfile.exists()) { // 文件存在时
				InputStream inStream = new FileInputStream(oldPath); // 读入原文件
				// 创建文件夹
				String folderName = newPath.substring(0, newPath.lastIndexOf("/"));
				File folder = new File(folderName);
				if (!folder.exists()) {
					folder.mkdirs();
				}
				FileOutputStream fs = new FileOutputStream(newPath);
				byte[] buffer = new byte[1444];
				while ((byteread = inStream.read(buffer)) != -1) {
//					bytesum += byteread; // 字节数 文件大小
					fs.write(buffer, 0, byteread);
				}
				inStream.close();
				fs.flush();
				fs.close();
				inStream = null;
				fs = null;
			} else {
				System.gc();
				return false;
			}
		} catch (Exception e) {
			log.error("复制单个文件操作出错");
			System.gc();
			return false;
		}
		System.gc();
		return true;
	}

	/**
	 * 将InputStream写入本地文件
	 * 
	 * @param saveAddress 写入本地目录（/Users/wangfuxin/Desktop/1.jpg）
	 * @param input       输入流
	 * @throws IOException
	 */
	public static JSONObject writeToLocal(String saveAddress, InputStream input) {
		JSONObject return_data = new JSONObject();
		int index;
		byte[] bytes = new byte[2048];
		FileOutputStream downloadFile;
		try {
			File saveFile = new File(saveAddress);
			downloadFile = new FileOutputStream(saveFile);
			try {
				while ((index = input.read(bytes)) != -1) {
					downloadFile.write(bytes, 0, index);
					downloadFile.flush();
				}
				downloadFile.close();
				downloadFile.flush();
				input.close();
				input = null;
				downloadFile = null;
			} catch (IOException e) {
				System.out.println(e.getMessage());
				return_data.put("res", false);
				return_data.put("exception", "文件保存失败");
				return return_data;
			}
		} catch (FileNotFoundException e) {
			return_data.put("res", false);
			return_data.put("exception", "文件保存失败");
			return return_data;
		}
		System.gc();
		return_data.put("res", true);
		return_data.put("exception", "文件保存成功");
		return return_data;
	}

	/**
	 * 复制种子文件
	 */
	public static Boolean copyFile(File sourceFile, File targetFile) {
		try {
			// 新建文件输入流并对它进行缓冲
			FileInputStream input = new FileInputStream(sourceFile);
			BufferedInputStream inBuff = new BufferedInputStream(input);

			// 新建文件输出流并对它进行缓冲
			FileOutputStream output = new FileOutputStream(targetFile);
			BufferedOutputStream outBuff = new BufferedOutputStream(output);

			// 缓冲数组
			byte[] b = new byte[1024 * 5];
			int len;
			while ((len = inBuff.read(b)) != -1) {
				outBuff.write(b, 0, len);
			}
			// 刷新此缓冲的输出流
			outBuff.flush();

			// 关闭流
			inBuff.close();
			outBuff.close();
			output.close();
			input.close();
			inBuff = null;
			outBuff = null;
			output = null;
			input = null;
		} catch (Exception e) {
			log.error("复制文件操作出错:" + e.getMessage());
			System.gc();
			return false;
		}
		System.gc();
		return true;
	}

	/**
	 * 将字符串写入文件中
	 * 
	 * @Title: WriteStringToFile
	 * @Description:
	 * @Author luoqilin
	 * @DateTime 2020-04-28 19:01:56
	 * @param filePath 文件路径
	 * @param str      写入的字符串
	 */
	public static boolean WriteStringToFile(String filePath, String str) {
		try {
			File file = new File(filePath);
			PrintStream ps = new PrintStream(new FileOutputStream(file));
			ps.append(str);// 在已有的基础上添加字符串

			ps.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
		return true;
	}

	/**
	 * @Title: readFileByPath
	 * @Description: 将文本文件转化为字符串
	 * @Author yuankaiqiang
	 * @DateTime 2021-01-12 14:06:28
	 * @param filePath
	 * @return
	 * @throws Exception
	 */
	public static String readFileByPath(String filePath) throws Exception {
		StringBuffer readBuffer = new StringBuffer();
		/************** 1.参数检测 **************/
		if (filePath == null || filePath.isEmpty()) {
			return readBuffer.toString();
		}
		/************** 2.读取数据 **************/
		try (FileReader fileReader = new FileReader(filePath);
				BufferedReader bufferedReader = new BufferedReader(fileReader)) {
			String line = bufferedReader.readLine();
			while (line != null) {
				readBuffer.append(line);
				line = bufferedReader.readLine();
			}
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
		return readBuffer.toString();
	}

	/**
	 * @Title: writeFileByPath
	 * @Description: 写入文件并返回
	 * @Author yuankaiqiang
	 * @DateTime 2021-01-12 14:14:47
	 * @param filePath
	 * @param content
	 * @return
	 * @throws Exception
	 */
	public static String writeFileByPath(String filePath, String content) throws Exception {
		StringBuffer readBuffer = new StringBuffer();
		/************** 1.参数检测 **************/
		if (filePath == null || filePath.isEmpty()) {
			throw new MyException(ExceptionType.OperationError, "请填写写入文件路径!");
		}
		if (content == null || content.isEmpty()) {
			return readBuffer.toString();
		}
		/************** 2.写入数据 **************/
		try (FileWriter fileWriter = new FileWriter(filePath);) {
			fileWriter.write(content);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return content;
	}
	
	
}
